package com.ly.web.controller.king;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.erp.CommonUtil;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.KingConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.KingBaseTaxRateCategoryEntity;
import com.ly.heart.domain.KingOrgEntity;
import com.ly.heart.domain.king.BaseChildBo;
import com.ly.heart.domain.king.base.BaseModelBo;
import com.ly.heart.domain.king.base.TaxCategoryBo;
import com.ly.heart.domain.king.base.TaxSystemBo;
import com.ly.heart.domain.request.KingBaseRequest;
import com.ly.heart.domain.response.KingBaseResponse;
import com.ly.heart.domain.response.KingBaseResponseError;
import com.ly.heart.domain.response.KingBaseResponseSuccessEntity;
import com.ly.heart.service.IKingBaseTaxRateCategoryService;
import com.ly.heart.service.IKingOrgService;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.heart.util.KingCommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Api ( value = "TaxCategoryRemote", tags = "基础数据-税种" )
@RestController
@RequestMapping ( "/heart/TaxCategoryRemote" )
@Slf4j
public class TaxCategoryRemote {

    @Resource
    private IKingOrgService iKingOrgService;
    @Resource
    private IKingBaseTaxRateCategoryService iKingBaseTaxRateCategoryService;

    @ApiOperation ( "拉取税种" )
    @GetMapping ( "/pull" )
    public AjaxResult pull () {
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity> ().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity :: getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        K3CloudApi client = new K3CloudApi ( identifyInfo );
        /**
         * 	 实体主键：FTAXTYPEID
         * 	 数据状态：FDocumentStatus
         * 	 禁用状态：FForbidStatus
         * 	 名称：FName  (必填项)
         * 	 编码：FNumber
         * 	 修改人：FModifierId
         * 	 创建人：FCreatorId
         * 	 创建日期：FCreateDate
         * 	 修改日期：FModifyDate
         * 	 描述：FDescription
         * 	 生效日期：FStartDate  (必填项)
         * 	 失效日期：FEndDate  (必填项)
         * 	 税收制度：FTaxSystemID  (必填项)
         * 	 纳税币种：FCurrencyID
         * 	 汇率类型：FRateTypeID
         * 	 申报机关：FDeclareORG
         * 	 征收机关：FLevyORG
         * 	 禁用日期：FForbidDate
         * 	 禁用人：FForbidderID
         * 	 审核人：FAuditorID
         * 	 审核日期：FAuditDate
         * 	 系统预置：FIsSysPreset
         * 	 税额精确度：FTaxPrecise
         * 	 最小会计单位：FMinAccountUnit
         * 	 舍入规则：FRoundRule  (必填项)
         * 	 允许改写税率：FIsModifyTaxRate
         * 	 允许改写和录入税额：FIsModifyAndRecordTax
         * 	 纳税允差百分比：FTaxTolerancePercentage
         * 	 纳税允差范围额：FTaxToleranceRange
         * 	 位置：FTempCountry
         */
        String jsonData = "{\"FormId\":\"" + KingConstUtil.BD_TAXTYPE + "\",\"FieldKeys\":\"FNumber,FName,FStartDate,FEndDate,FTaxSystemID.FNumber,FCurrencyID.FNumber,FIsModifyTaxRate,FIsModifyAndRecordTax,FTaxToleranceRange,FTaxTolerancePercentage \",\"FilterString\":[],\"OrderString\":\"\",\"TopRowCount\":0,\"StartRow\":0,\"Limit\":2000,\"SubSystemId\":\"\"}";
        List<List<Object>> lists = null;
        try {
            lists = client.executeBillQuery ( jsonData );
            for ( int i = 0; i < lists.size (); i++ ) {
                List<Object> objects = lists.get ( i );
                log.info ( "-->{}", objects );
                KingBaseTaxRateCategoryEntity one = iKingBaseTaxRateCategoryService.getOne ( new LambdaQueryWrapper<KingBaseTaxRateCategoryEntity> ().eq ( KingBaseTaxRateCategoryEntity :: getDocNo, String.valueOf ( objects.get ( 0 ) ) ) );
                if ( one == null ) {
                    one = new KingBaseTaxRateCategoryEntity ();
                    one.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
                    one.setDocNo ( String.valueOf ( objects.get ( 0 ) ) );
                    one.setTitle ( String.valueOf ( objects.get ( 1 ) ) );
                    one.setEffectiveDate ( CommonUtil.parseDate ( String.valueOf ( objects.get ( 2 ) ) ) );
                    one.setExpiringDate ( CommonUtil.parseDate ( String.valueOf ( objects.get ( 3 ) ) ) );
                    one.setTaxRateSystemCode ( String.valueOf ( objects.get ( 4 ) ) );
                    one.setTaxCurrency ( String.valueOf ( objects.get ( 5 ) ) );
                    Boolean b = new Boolean ( String.valueOf ( objects.get ( 6 ) ) );
                    one.setIsAllowRewriting ( b ? 1 : 2 );
                    b = new Boolean ( String.valueOf ( objects.get ( 6 ) ) );
                    one.setIsAllowLimit ( b ? 1 : 2 );
                    one.setTaxToleranceRange ( String.valueOf ( objects.get ( 7 ) ) );
                    one.setTaxTolerancePercentage ( String.valueOf ( objects.get ( 8 ) ) );
                    one.setCreateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
                    one.setCreateTime ( DateUtils.getNowDate () );
                    one.setIsSend ( KingConstUtil.KING_DATA_IS_SEND_YES );
                    iKingBaseTaxRateCategoryService.save ( one );
                }
            }
        } catch ( Exception e ) {
            e.printStackTrace ();
            return AjaxResult.error ( "同步税种失败" );
        }
        return AjaxResult.success ( "同步税种完成" );
    }

    @ApiOperation ( "拉取税种" )
    @GetMapping ( "/push" )
    public AjaxResult push () {
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity> ().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity :: getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        K3CloudApi client = new K3CloudApi ( identifyInfo );
        //获取所有可推税种
        List<KingBaseTaxRateCategoryEntity> list = iKingBaseTaxRateCategoryService.list ( new LambdaQueryWrapper<KingBaseTaxRateCategoryEntity> ().
                eq ( KingBaseTaxRateCategoryEntity :: getIsUsed, ConstUtil.IS_USED_YES ).
                eq ( KingBaseTaxRateCategoryEntity :: getIsDisabled, 1 ).
                eq ( KingBaseTaxRateCategoryEntity :: getIsSend, KingConstUtil.KING_DATA_IS_SEND_NO ) );
        if ( CollectionUtils.isEmpty ( list ) ) {
            return AjaxResult.error ( "暂无新数据可推！" );
        }
        try {
            batchSave ( list, client );
            submit ( list, client );
            audit ( list, client );
        } catch ( Exception e ) {
            return AjaxResult.error ( "推送税种失败！" );
        }
        return AjaxResult.success ( "推送税种完成" );
    }

    /**
     * 推送结算方式
     *
     * @param list
     * @param client
     * @throws Exception
     */
    private void batchSave ( List<KingBaseTaxRateCategoryEntity> list, K3CloudApi client ) throws Exception {
        KingBaseRequest request = new KingBaseRequest ();
        List<BaseModelBo> bos = new ArrayList<> ();
        list.forEach ( taxRateEntity -> {
            TaxCategoryBo bo = new TaxCategoryBo ();
            //税种和税种按对象处理
            bo.setFNumber ( taxRateEntity.getDocNo () );
            bo.setFName ( taxRateEntity.getTitle () );
            BaseChildBo base = new BaseChildBo ().setFNumber ( taxRateEntity.getTaxRateSystemCode () );
            bo.setFTaxSystemID ( base );
            base = new BaseChildBo ().setFNumber ( taxRateEntity.getTaxCurrency () );
            bo.setFCurrencyID ( base );
            bo.setFRoundRule ( String.valueOf ( taxRateEntity.getRoundingRules () ) );
            bo.setFIsModifyTaxRate ( taxRateEntity.getIsAllowRewriting () == 1 ? true : false );
            bo.setFIsModifyAndRecordTax ( taxRateEntity.getIsAllowLimit () == 1 ? true : false );
            bo.setFTaxTolerancePercentage ( taxRateEntity.getTaxTolerancePercentage () );
            bo.setFTaxToleranceRange ( taxRateEntity.getTaxToleranceRange () );
            bo.setFStartDate ( CommonUtil.getDateStrFormat ( taxRateEntity.getEffectiveDate (), "yyyy-MM-dd HH:mm:ss" ) );
            bo.setFEndDate ( CommonUtil.getDateStrFormat ( taxRateEntity.getExpiringDate (), "yyyy-MM-dd HH:mm:ss" ) );
            bos.add ( bo );
        } );
        request.setModel ( bos );
        String s = JSONObject.toJSONString ( request );
        log.info ( "bos-》{}", bos );
        log.info ( "s->{}", s );
        String resultJson = client.batchSave ( KingConstUtil.BD_TAXTYPE, s );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            //添加成功，进行提交
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "税种-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.info ( "{} 推送成功", sb );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "税种-推送失败：【" + sb + "】" );
        }
    }


    /**
     * 提交结算方式
     *
     * @param list
     * @param client
     */
    private void submit ( List<KingBaseTaxRateCategoryEntity> list, K3CloudApi client ) throws Exception {
        TaxSystemBo bo = new TaxSystemBo ();
        List<String> strings = new ArrayList<> ();
        list.forEach ( taxRateEntity -> {
            strings.add ( taxRateEntity.getDocNo () );
        } );
        bo.setNumbers ( strings );
        String jsonData = JSON.toJSONString ( bo );
        String resultJson = client.submit ( KingConstUtil.BD_TAXTYPE, jsonData );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            //提交成功
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "税种-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.error ( "{} 提交成功", sb );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "税种-提交失败：【" + sb + "】" );
        }
    }

    /**
     * 结算方式审核
     *
     * @param list
     * @param client
     */
    private void audit ( List<KingBaseTaxRateCategoryEntity> list, K3CloudApi client ) throws Exception {
        TaxSystemBo bo = new TaxSystemBo ();
        List<String> strings = new ArrayList<> ();
        list.forEach ( taxRateEntity -> {
            strings.add ( taxRateEntity.getDocNo () );
        } );
        bo.setNumbers ( strings );
        String jsonData = JSON.toJSONString ( bo );
        String resultJson = client.audit ( KingConstUtil.BD_TAXTYPE, jsonData );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "税种-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.info ( "{} 审核成功", sb );
            list.forEach ( taxRateEntity -> {
                iKingBaseTaxRateCategoryService.update ( new LambdaUpdateWrapper<KingBaseTaxRateCategoryEntity> ().
                        set ( KingBaseTaxRateCategoryEntity :: getIsSend, KingConstUtil.KING_DATA_IS_SEND_YES ).
                        eq ( KingBaseTaxRateCategoryEntity :: getDocNo, taxRateEntity.getDocNo () ) );
            } );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "税种-审核失败：【" + sb + "】" );
        }
    }

}
